<script setup lang="ts">
import { ElMessage } from 'element-plus';
import { ref, watch } from 'vue';

interface Props {
  modelValue?: boolean;
  content?: string;
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void;
  (e: 'update:content', value: string): void;
  (e: 'save', content: string): void;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  content: '',
});

const emit = defineEmits<Emits>();

const visible = ref(false);
const content = ref('');

watch(() => props.modelValue, (val) => {
  visible.value = val;
  if (val) {
    content.value = props.content;
  }
});

watch(() => props.content, (val) => {
  content.value = val;
});

watch(visible, (val) => {
  emit('update:modelValue', val);
});

function handleClose() {
  visible.value = false;
}

function handleSave() {
  emit('update:content', content.value);
  emit('save', content.value);
  visible.value = false;
  ElMessage.success('保存成功');
}

function handleInput(text: string) {
  content.value = text;
  emit('update:content', text);
}
</script>

<template>
  <el-dialog
    v-model="visible"
    title="编辑 Markdown 内容"
    width="90%"
    :before-close="handleClose"
    class="markdown-editor-dialog"
  >
    <div class="editor-container">
      <v-md-editor
        v-model="content"
        height="500px"
        @change="handleInput"
      />
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">
          取消
        </el-button>
        <el-button type="primary" @click="handleSave">
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.markdown-editor-dialog {
  .editor-container {
    height: 500px;
  }
  .dialog-footer {
    display: flex;
    gap: 12px;
    justify-content: flex-end;
  }
}
:deep(.el-dialog__body) {
  padding: 20px;
}
:deep(.el-dialog) {
  margin-top: 5vh !important;
}
</style>
